package com.software.frontend.searchmovie.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.software.frontend.R;
import com.software.frontend.searchmovie.utils.LoadingDialog;
import com.software.frontend.searchmovie.adapter.MovieAdapter;
import com.software.frontend.searchmovie.entity.Movie;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SearchMovieResultActivity extends AppCompatActivity {

    private SearchView sv_text;
    private Button btn_search;
    private ImageButton iBtn_return;
    private ListView lv_movie;
    private String searchStr;
    private List<Movie> movies;

    private MovieAdapter movieAdapter;
    private Dialog dialog;
    private String sessionId;
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            switch (msg.what){
                case 1:
                    //绑定适配器
                    movieAdapter = new MovieAdapter(SearchMovieResultActivity.this,movies, R.layout.item_listview_search_movie_result);
                    lv_movie.setAdapter(movieAdapter);
                    dialog.dismiss();//数据加载完成取消弹窗
                    break; default:
                        break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_movie_result);
        //初始化控件对象
        getViews();
        //获取搜索字符串
        Intent intent = getIntent();
        searchStr = intent.getStringExtra("searchStr");
        sv_text.setQuery(searchStr, false);
        //设置点击事件监听器
        setLintener();
        //加载弹窗
        LoadingDialog.Builder loadBuilder = new LoadingDialog.Builder(this)
                .setMessage("加载中...")
                .setCancelable(true)//返回键是否可点击
                .setCancelOutside(false);//窗体外是否可点击
        dialog = loadBuilder.create();
        dialog.show();//显示弹窗
        //从服务器端获取数据
        getData();





    }

    private void setLintener() {
        lv_movie.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Log.e("abcd", movies.get(i).getId() + "被点击了");
                Intent intent = new Intent(SearchMovieResultActivity.this, SearchMovieResultDetailActivity.class);
                int movieId = movies.get(i).getId();
                intent.putExtra("movieId", movieId);
                intent.putExtra("searchStr", searchStr);
                intent.putExtra("movieName", movies.get(i).getName());
                intent.putExtra("sessionId", sessionId);
                startActivity(intent);
            }
        });

        btn_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SearchMovieResultActivity.this, SearchMovieResultActivity.class);
                String str = sv_text.getQuery().toString();
                intent.putExtra("searchStr", str);
                startActivity(intent);
                finish();
            }
        });

        iBtn_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


    }

    private void getData() {
        //向服务发送异步的GET请求R
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(getString(R.string.localhost) + "searchMovie/findMovie?searchStr=" + searchStr)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                dialog.dismiss();
                Looper.prepare();
                Toast.makeText(SearchMovieResultActivity.this, "请求出错啦！请重试！", Toast.LENGTH_SHORT).show();
                Looper.loop();
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Headers headers =response.headers();//response为okhttp请求后的响应
                List cookies = headers.values("Set-Cookie");
                if (cookies == null){
                    finish();
                }
                String session = cookies.get(0).toString();
                sessionId = session.substring(0,session.indexOf(";"));
                String jsonStr = response.body().string();
                Type type = new TypeToken<List<Movie>>(){}.getType();
                movies = new Gson().fromJson(jsonStr,type);
                Log.e("abcd", movies.toString());
                Message msg = new Message();
                msg.what = 1;
                myHandler.sendMessage(msg);
            }
        });
//        movies = new ArrayList<>();
//        Movie movie1 = new Movie();
//        movie1.setId(1);
//        movie1.setName("蜘蛛唐人街探案");
//        movie1.setTime(new Date());
//        movie1.setType("喜剧、冒险");
//        movie1.setLanguage("英语");
//        movie1.setCoverUrl("https://img.tt98.com/d/file/tt98/20200103134945341/e08ff425f0.jpg");
//        movies.add(movie1);
//
//        Movie movie2 = new Movie();
//        movie2.setId(2);
//        movie2.setName("蜘蛛侠");
//        movie2.setTime(new Date());
//        movie2.setType("冒险");
//        movie2.setLanguage("英语");
//        movie2.setCoverUrl("http://rna5ai3pz.hb-bkt.clouddn.com/video/2FE35C686B4C6B634E5DA8CB1F59510D.png");
//        movies.add(movie2);
//
//        Movie movie3 = new Movie();
//        movie3.setId(3);
//        movie3.setName("蜘蛛22侠");
//        movie3.setTime(new Date());
//        movie3.setType("冒险22");
//        movie3.setLanguage("英语22");
//        movie3.setCoverUrl("https://img.tt98.com/d/file/tt98/20200103134945341/e08ff425f0.jpg");
//        movies.add(movie3);
//
//        Movie movie4 = new Movie();
//        movie4.setId(4);
//        movie4.setName("蜘蛛1122侠");
//        movie4.setTime(new Date());
//        movie4.setType("冒险1122");
//        movie4.setLanguage("英语22122");
//        movie4.setCoverUrl("https://img.tt98.com/d/file/tt98/20200103134945341/e08ff425f0.jpg");
//        movies.add(movie4);


    }

    private void getViews() {
        btn_search = findViewById(R.id.search_movie_request_btn_search);
        iBtn_return = findViewById(R.id.search_movie_request_btn_return);
        sv_text = findViewById(R.id.search_movie_request_search_view);
        lv_movie = findViewById(R.id.search_movie_result_lv);
    }


}